(function () {
  const OTA_MEI_TUAN = "meiTuan";
  const OTA_CTRIP = "trip";
  let pageIdx = 0;
  let isMeituanPulling = false;

  window.addEventListener("message", (event) => {
    const { data } = event;

    if (!data) {
      return;
    }

    const msgType = data.msgType;

    switch (msgType) {
      case PULL_MEI_TUAN_CANCELED:
      case PULL_MEI_TUAN_AWAIT_CHECKIN:
        pageIdx = data?.pageIdx ?? 0;
        isMeituanPulling = true
        setTimeout(() => {
          isMeituanPulling = false
        }, 3000)
        break;
      case PULL_CTRIP:
        pageIdx = data?.pageIdx || 1;
        break;
    }
  });

  const meiTuanOrderListUrl = "/ebooking/orders/list";
  const meiTuanOrderListUrl2 = "/ebooking/orders?";
  const meiTuanOrderDetailUrlReg = /\/ebooking\/orders\/\d+/;
  const ctripOrderListUrl = "/order/domestic/allOrderList";
  const meiTuanNewOrderUrl = "/auto/account";
  const meiTuanNewOrderUrl2 = "/unhandled/count";
  const meiTuanCancelOrderUrl = "/notice/order/list";
  const ctripNewOrderUrl = "/ebkorderv2/api/trace/set";
  const ctripCancelOrderUrl = "/queryOrderCount"
  const ctripOrderDetailUrl = "/ebkorderv2/api/order/domestic/orderDetail";

  if (ajaxHooker) {
    ajaxHooker.hook((request) => {
      const url = request.url;

      // 监听新订单或取消订单
      if ([meiTuanNewOrderUrl, meiTuanNewOrderUrl2, meiTuanCancelOrderUrl, ctripNewOrderUrl, ctripCancelOrderUrl].some((t) => url?.includes(t))) {
        postMessage({
          msgType: REFRESH_ORDER_LIST,
        });
      }
    });
  }

  function modifyRequest(request = {}, ota, needChangeRequest = true, needSendResponse = false) {
    if (needChangeRequest) {
      const body = JSON.parse(request.data);
      body.pageIdx = ota === OTA_MEI_TUAN ? pageIdx : pageIdx || 1;
      request.data = JSON.stringify(body);
    }

    if (ota === OTA_MEI_TUAN && isMeituanPulling) {
      const url = request.url;

      if (url?.includes(meiTuanOrderListUrl2)) {
        const index = url.indexOf('?')

        if (index > -1) {
          const params = new URLSearchParams(url.substring(index))
          const filter = params.get('filter')
          const orderStatus = params.get('orderStatus')
          params.set('offset', (pageIdx * 10).toString())

          if (filter === 'ALL' && !orderStatus) {
            params.set('orderStatus', 'CANCELED')
          }

          request.url = url.substring(0, index) + '?' + params.toString()
        }
      }

    }

    request.response = function (event) {
      const response = JSON.parse(event.response);

      if (needSendResponse && response) {
        let data = response

        if (ota === OTA_MEI_TUAN) {
          data = response.data
        }

        const results = [data];
        postMessage({
          msgType: "response",
          ota,
          data: results,
        });
      }
    };
  }
})();
